package website

import (
	"strings"

	iris "gopkg.in/kataras/iris.v6"
)

//Login *
type Login struct{}

//Main *
func (l *Login) Main(ctx *iris.Context) {
	ctx.Render("login.html", nil)
}

//Logout *
func (l *Login) Logout(ctx *iris.Context) {
	ctx.Session().Delete("user_info")
	ctx.Redirect("/")
}

//Login *
func (l *Login) Login(ctx *iris.Context) {
	addr := formValue(ctx, "addr")
	username := formValue(ctx, "username")
	password := formValue(ctx, "password")

	result := Result{}

	ssh, err := NewSSH(username, password, addr)
	if nil != err {
		LogDebugln(err)
		result.Ok = false
		ctx.JSON(iris.StatusOK, result)
		return
	}

	if _, err := ssh.Connect(); nil != err {
		LogDebugln(err)
		result.Ok = false
		ctx.JSON(iris.StatusOK, result)
	} else {

		ctx.Session().Set("user_info", User{
			User: username,
			Pwd:  password,
			Addr: addr,
		})

		result.Ok = true
		result.Data = "/"
		result.Msg = "ok"
		ctx.JSON(iris.StatusOK, result)
	}
}

//FormValue *
func formValue(ctx *iris.Context, key string) string {
	return strings.TrimSpace(ctx.FormValue(key))
}

func init() {
	login := &Login{}
	Get("/login", login.Main)
	Get("/logout", login.Logout)
	Post("/login", login.Login)
}
